package com.kcs.fxmargin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.kcs.common.utils.Constant;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.model.TDealsSettle;
import com.kcs.fxmargin.service.CommonService;
import com.kcs.fxmargin.service.DealsService;

/**
 * Servlet implementation class ValidateSettlementServlet
 */
public class ValidateSettlementServlet extends HttpServlet {
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	
	private static final long serialVersionUID = 1L;
	private static final String CONTENT_TYPE = "text/html; charset=utf-8";	

    private CommonService common = new CommonService();
    private DealsService service = new DealsService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ValidateSettlementServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        response.setContentType(CONTENT_TYPE);
        
        System.out.println("ValidateSettlementServlet : Start");
      
        LoginActionForm loginBean = null;
        
        try {
        	
        	HttpSession session = request.getSession();
        	
        	if(session == null) {
        		JSONObject json = new JSONObject();
                json.put("data", "to");
                json.write(out);
        	} else {
        		loginBean = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
            	
            	String objData = request.getParameter("objData");
            	 
            	System.out.println("objData = " + objData);

            	JSONArray jsonArray = new JSONArray(objData);
            	
            	System.out.println(jsonArray);
            	
            	List<TDealsSettle> dealsSettleList = new ArrayList<TDealsSettle>();
            	TDealsSettle dealsSettle 	= null;
            	int rowVersion 				= 0;
            	String result 				= "";
            	String userId				= "";
            	
            	if(loginBean != null) {
            		userId = loginBean.getUserId();
            	}
            	
            	stop:
            	for(int i = 0 ; i < jsonArray.length() ; i++){
            		System.out.println("settleAmount[" + (i+1) + "] 	= " + jsonArray.getJSONObject(i).get("settleAmount"));
            		System.out.println("settleRemain[" + (i+1) + "]  	= " + jsonArray.getJSONObject(i).get("settleRemain"));
            		System.out.println("dealsSettleId[" + (i+1) + "] 	= " + jsonArray.getJSONObject(i).get("dealsSettleId"));
            		System.out.println("rowVersion[" + (i+1) + "]  		= " + jsonArray.getJSONObject(i).get("rowVersion"));
            		System.out.println("dealId[" + (i+1) + "]  			= " + jsonArray.getJSONObject(i).get("dealId"));
            		
            		dealsSettle = new TDealsSettle();
            		dealsSettle.setId((String)jsonArray.getJSONObject(i).get("dealsSettleId"));
            		dealsSettle.setDealId((String)jsonArray.getJSONObject(i).get("dealId"));
            		dealsSettle.setSettleAmount(stringToBigDecimal((String)jsonArray.getJSONObject(i).get("settleAmount")));
            		dealsSettle.setSettleRemain(stringToBigDecimal((String)jsonArray.getJSONObject(i).get("settleRemain")));
            		dealsSettle.setRowVersion(stringToInteger((String)jsonArray.getJSONObject(i).get("rowVersion")));
            		dealsSettle.setCreateby(userId);
            		dealsSettle.setUpdateBy(userId);
            		
            		rowVersion = common.getRowVersion(Constant.DEALS_SETTLE, dealsSettle.getId());
            		
            		if(rowVersion <= dealsSettle.getRowVersion()){
            			dealsSettle.setRowVersion(rowVersion + 1);
            			dealsSettleList.add(dealsSettle);
            		} else {
            			log.error("Concurrent Data Access." + Constant.DEALS_SETTLE + " [id = " + dealsSettle.getId() + "]");
            			result = "dup_row";
            			break stop;
            		}
            		
            	}
            	
            	if(!"dup_row".equals(result)) result = service.update(dealsSettleList);
            	
            	JSONObject json = new JSONObject();
                json.put("data", result);
                json.write(out);
        	}
        	
            
        } catch (Exception e) {
        	log.error(e);
            out.print("{\"status\": \"failed\", \"message\": \"" +
                      e.getMessage() + "\"}");
            
        } finally {
            out.close();
        }

        System.out.println("ValidateSettlementServlet : End");
		
	}
	
	
	public BigDecimal stringToBigDecimal(String number) throws Exception {
		BigDecimal result = null;
		
		if(number != null && !"".equals(number)) result = new BigDecimal(number);
		
		return result;
	}

	public Integer stringToInteger(String number) throws Exception {
		Integer result = null;
		
		if(number != null && !"".equals(number)) result = Integer.parseInt(number);
		
		return result;
	}
}
